package com.example.havi.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.example.havi.bean.HyChatUser;
import com.example.havi.interfaces.HyphenateLibraryCallBack;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.util.ChatToastUtil;
import com.example.havi.util.GsonUtils;
import com.example.havi.util.LogUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.example.havi.util.PlayerUtil;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;

public class ChatHelper {
    private static ChatHelper instance;
    private Context appContext;
    private HyChatUser hyChatUser;



    private HyphenateLibraryCallBack hyphenateLibraryCallBack;
    private EMMessageListener messageListener;

    public synchronized static ChatHelper getInstance() {
        if (instance == null) {
            instance = new ChatHelper();
        }
        return instance;
    }

    public void init(Context appContext, HyphenateLibraryCallBack callBack) {
        this.appContext = appContext;
        hyphenateLibraryCallBack = callBack;
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        // 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
        // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);

        //是否显示对方已读
        options.setRequireAck(true);
        // 是否显示已发送
        options.setRequireDeliveryAck(false);

        //初始化
        EMClient.getInstance().init(appContext, options);

        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);

        EmojiDataHelper.getInstence().init(appContext);
        Log.e("frank","环信已经初始化");
        registerMessageListener();  //注册消息接收监听
    }

    private void registerMessageListener() {
        messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    // in background, do not refresh UI, notify it in notification bar
                    PlayerUtil.INSTANCE.playerVibrator();
                    PlayerUtil.INSTANCE.playSystemMusic();
                    //显示消息通知
                    getLibraryCallBack().onNewMsg(message);
                    try {
                        //基本信息 头像等信息 通过扩展字段 ext传递
                        String ext = message.getStringAttribute("ext");
                        LogUtil.e("frank", "接收到聊天消息："
                                + "\n ext = " + ext
                                + "\n ChatType = " + message.getChatType()
                                + "\n messageBody = " + message.getBody()
                                + "\n messageForm = " + message.getFrom()
                                + "\n messageTo = " + message.getTo());
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {

            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
            }

            @Override
            public void onMessageRecalled(List<EMMessage> messages) {

            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
            }
        };

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    public Context getAppContext() {
        return appContext;
    }

    public HyphenateLibraryCallBack getLibraryCallBack() {
        return hyphenateLibraryCallBack;
    }

    public void setHyphenateLibraryCallBack(HyphenateLibraryCallBack hyphenateLibraryCallBack) {
        this.hyphenateLibraryCallBack = hyphenateLibraryCallBack;
    }

    /**
     * 同步账号信息
     *
     * @param userInfo
     */
    public void syncChatUserInfo(HyChatUser userInfo) {
        this.hyChatUser = userInfo;
    }

    public HyChatUser getHyChatUser() {
        return hyChatUser==null?new HyChatUser():hyChatUser;
    }


    //环信登陆
    public void login(String chat_userName, String chat_password){
       login(chat_userName, chat_password, new LoginCallBack() {
           @Override
           public void onSuccess() {

           }

           @Override
           public void onError(int code, String message) {

           }
       });
    }
    public void login(String chat_userName, String chat_password, final LoginCallBack callBack){
        if(!TextUtils.isEmpty(chat_userName)&& !TextUtils.isEmpty(chat_password)){
            EMClient.getInstance().login(chat_userName,chat_password,new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Log.e("frank", "登录聊天服务器成功！");
                    callBack.onSuccess();
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.e("frank", "登录聊天服务器失败！"+message);
                    callBack.onError(code,message);
                }
            });
        }else{
            Log.e("frank","环信账号不可用,无法登陆 "+chat_userName+" : "+chat_password);
            ChatToastUtil.showToast(getAppContext(),"环信账号不可用,无法登陆 "+chat_userName+" : "+chat_password);
        }
    }

    public boolean isLogin() {
        return EMClient.getInstance().isConnected();    //是否登录（连接服务器）
    }

    //退出环信登陆
    public void loginOut(){
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                Log.d("frank", "环信退出登录成功");

            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub
                Log.d("frank", "环信退出登录错误"+code+"  "+message);
            }
        });
    }

}
